package com.huxiu.yd;

import com.google.gson.Gson;

import com.android.volley.Request.Method;
import com.android.volley.Response.Listener;
import com.huxiu.yd.net.GsonRequest;
import com.huxiu.yd.net.NetworkConstants;
import com.huxiu.yd.net.NetworkHelper;
import com.huxiu.yd.net.model.ArticleItem;
import com.huxiu.yd.net.model.Comment;
import com.huxiu.yd.net.model.SpareItem;
import com.huxiu.yd.net.responses.ArticlesResponse;
import com.huxiu.yd.net.responses.SpareItemResponse;
import com.huxiu.yd.utils.Constants;
import com.huxiu.yd.utils.Global;
import com.huxiu.yd.utils.ImageUtils;
import com.huxiu.yd.utils.LogUtils;
import com.huxiu.yd.utils.Utils;
import com.huxiu.yd.view.ArticleView;
import com.huxiu.yd.view.AvatarView;
import com.huxiu.yd.view.CommentViewHolder;
import com.huxiu.yd.view.SpareItemViewHolder;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.viewpagerindicator.CirclePageIndicator;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;

import java.util.LinkedHashMap;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.InjectView;


public class SpareDetailActivity extends BaseActivity implements OnClickListener {

    @InjectView(R.id.back)
    ImageView back;

    @InjectView(R.id.title)
    TextView title;

    @InjectView(R.id.right_image)
    ImageView rightImage;

    @InjectView(R.id.right_text)
    TextView rightText;

    @InjectView(R.id.web)
    WebView web;

    @InjectView(R.id.like_count)
    TextView likeCount;

    @InjectView(R.id.comment)
    TextView comment;

    @InjectView(R.id.bottom_bar)
    ViewGroup bottomBar;

    @InjectView(R.id.content_container)
    ViewGroup contentContainer;

    @InjectView(R.id.web_title)
    TextView webTitle;

    @InjectView(R.id.title_image)
    View titleImage;

    @InjectView(R.id.title_image_pager)
    ViewPager titleImagePager;

    @InjectView(R.id.price)
    TextView price;

    @InjectView(R.id.avatar)
    AvatarView avatar;

    @InjectView(R.id.username)
    TextView username;

    @InjectView(R.id.release_time)
    TextView releaseTime;

    @InjectView(R.id.city)
    TextView city;

    @InjectView(R.id.seller_info)
    ViewGroup sellerInfo;

    @InjectView(R.id.like_layout)
    FrameLayout likeLayout;

    @InjectView(R.id.massive_test_bottom)
    LinearLayout massiveTestBottom;

    @InjectView(R.id.spare_comment_count)
    TextView spareCommentCount;

    @InjectView(R.id.spare_comment_layout)
    FrameLayout spareCommentLayout;

    @InjectView(R.id.spare_like_count)
    TextView spareLikeCount;

    @InjectView(R.id.spare_like_layout)
    FrameLayout spareLikeLayout;

    @InjectView(R.id.spare_contact_button)
    Button spareContactButton;

    @InjectView(R.id.spare_bottom)
    LinearLayout spareBottom;

    @InjectView(R.id.discovery_bottom)
    LinearLayout discoveryBottom;

    @InjectView(R.id.indicator)
    CirclePageIndicator indicator;

    @InjectView(R.id.title_pager_container)
    FrameLayout titlePagerContainer;

    private SpareItem item;

    private PagerAdapter mPagerAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_discovery_detail);
        ButterKnife.inject(this);
        back.setOnClickListener(this);
        initViewPagerLayout();
        titleImage.setVisibility(View.GONE);
        rightText.setVisibility(View.GONE);
        rightImage.setImageResource(R.drawable.ic_share);
        rightImage.setVisibility(View.VISIBLE);
        discoveryBottom.setVisibility(View.GONE);
        massiveTestBottom.setVisibility(View.GONE);
        spareBottom.setVisibility(View.VISIBLE);
        spareLikeLayout.setOnClickListener(this);
        spareCommentLayout.setOnClickListener(this);
        spareContactButton.setOnClickListener(this);
        rightImage.setOnClickListener(this);
        String data = getIntent().getStringExtra(Constants.DISCOVERY_ITEM_KEY);
        item = new Gson().fromJson(data, SpareItem.class);
        updateWebViewSettings(web);
        reloadUIData();
        loadServerData();
    }

    private void initViewPagerLayout() {
        titleImagePager.setVisibility(View.VISIBLE);
        titlePagerContainer.setVisibility(View.VISIBLE);
        LayoutParams params = (LayoutParams) titlePagerContainer.getLayoutParams();
        params.width = Global.screenWidth;
        params.height = Global.preferredImageHeight;
        titlePagerContainer.setLayoutParams(params);
        FrameLayout.LayoutParams params2 = (FrameLayout.LayoutParams) titleImagePager
                .getLayoutParams();
        params2.width = Global.screenWidth;
        params2.height = Global.preferredImageHeight;
        titleImagePager.setLayoutParams(params2);
    }

    void reloadUIData() {
        title.setText(R.string.spare);
        webTitle.setText(item.title);
        mPagerAdapter = new PagerAdapter() {
            @Override
            public int getCount() {
                return item.images == null ? 0 : item.images.length;
            }

            @Override
            public boolean isViewFromObject(View view, Object object) {
                return view == object;
            }

            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                container.removeView((View) object);
            }

            @Override
            public Object instantiateItem(ViewGroup container, final int position) {
                final String url = item.images[position];
                LogUtils.d("url is " + url);
                View view = getLayoutInflater()
                        .inflate(R.layout.spare_item_pager_item_view, container, false);
                ImageView imageView = (ImageView) view.findViewById(R.id.image);
                ViewGroup.LayoutParams params = imageView.getLayoutParams();
                int margin = Utils.dip2px(20);
                params.width = Global.screenWidth - margin;
                params.height = Global.preferredImageHeight - margin * 9 / 16;
                imageView.setLayoutParams(params);
                ImageLoader.getInstance().displayImage(url, imageView, ImageUtils
                        .getProductDisplayOption(R.drawable.default_product_image));
                container.addView(view);
                view.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(SpareDetailActivity.this, ViewImageActivity
                                .class);
                        intent.putExtra("urls", item.images);
                        intent.putExtra("pos", position);
                        startActivity(intent);
                    }
                });
                return view;
            }
        };
        titleImagePager.setAdapter(mPagerAdapter);
        if (item.images != null) {
            indicator.setViewPager(titleImagePager);
            indicator.setVisibility(View.VISIBLE);
        }
        updateLikeView();
        spareCommentCount.setText(Integer.toString(item.comment_num));
        spareCommentCount.setTextColor(getResources().getColor(R.color.gray3));
        spareCommentCount.setCompoundDrawablesWithIntrinsicBounds(R.drawable.comment_normal, 0,
                0, 0);
        webviewSetContent(web, item.content);
        sellerInfo.setVisibility(View.VISIBLE);
        price.setText("￥" + item.price);
        city.setText(item.city_name);
        avatar.setUserInfo(item.user_id, item.avatar, item.name);
        username.setText(item.name);
        username.setCompoundDrawablesWithIntrinsicBounds(0, 0, item.getUserDrawable(), 0);
        releaseTime.setText(Utils.getDateString(item.create_time));
    }

    public void updateLikeView() {
        spareLikeCount.setText(Integer.toString(item.like_num));
        spareLikeCount.setTextColor(getResources().getColor(item.liked() ? R.color.gray5 : R.color
                .gray3));
        spareLikeCount.setCompoundDrawablesWithIntrinsicBounds(
                item.liked() ? R.drawable.favorite_yes : R.drawable.favorite_no, 0, 0, 0);
    }

    void loadServerData() {
        String url = NetworkConstants.GOODS_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("user_goods_id", item.user_goods_id);
        params.put("act", "contents");
        GsonRequest<SpareItemResponse> request = new GsonRequest<>(url, Method.POST,
                SpareItemResponse.class, true, params, new Listener<SpareItemResponse>() {
            @Override
            public void onResponse(SpareItemResponse response) {
                if (response.isSuccess()) {
                    item = response.data;
                    reloadUIData();
                    if (response.comment != null || response.featured_comment != null) {
                        bindComments(response);
                    }
                } else {
                    Utils.showToast(response.msg);
                }
            }
        }, mErrorListener);
        NetworkHelper.getInstance().addToRequestQueue(request);
//        NetworkHelper.getInstance().getRequestQueue().start();
        getRelatedArticles();
    }

    private void bindComments(SpareItemResponse response) {
        int length = response.comment.length;
        for (int i = 0; i < length && i < 5; i++) {
            Comment comment = response.comment[i];
            View view = getLayoutInflater()
                    .inflate(R.layout.comment_list_item, contentContainer, false);
            bindCommentView(length, i, comment, view, false);
            contentContainer.addView(view);
        }
        if (length > 5) {
            View viewMore = getLayoutInflater()
                    .inflate(R.layout.view_more_comments, contentContainer, false);
            viewMore.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    launchReviewListActivity();
                }
            });
            contentContainer.addView(viewMore);
            View divider = new View(this);
            divider.setLayoutParams(new LayoutParams(1, Utils.dip2px(8)));
            contentContainer.addView(divider);
        }
        if ((response.featured_comment == null || response.featured_comment.length == 0)
                && (response.comment == null || response.comment.length == 0)) {
            View view = getLayoutInflater()
                    .inflate(R.layout.empty_comments_view, contentContainer, false);
            View firstComment = view.findViewById(R.id.no_review);
            firstComment.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(SpareDetailActivity.this,
                            SubmitCommentActivity.class);
                    intent.putExtra(Constants.SPARE_ID_KEY, item.user_goods_id);
                    startActivityForResult(intent, 0);
                }
            });
            contentContainer.addView(view);
        }
    }

    private void launchReviewListActivity() {
        Intent intent = new Intent(SpareDetailActivity.this,
                ReviewListActivity.class);
        intent.putExtra(Constants.SPARE_ID_KEY, item.user_goods_id);
        startActivity(intent);
    }

    private void bindCommentView(int length, int i, final Comment comment, View view,
                                 boolean isFeatured) {
        final CommentViewHolder vh = new CommentViewHolder(view);
        vh.header.setVisibility(i == 0 ? View.VISIBLE : View.GONE);
        vh.bottomDivider.setVisibility(View.VISIBLE);
        vh.avatar.setUserInfo(comment.user_id, comment.avatar, comment.name);
        if (isFeatured) {
            vh.commentHeader.setText(R.string.featured_comment);
        } else {
            vh.commentHeader.setText(getString(R.string.comment) + "(" + length + ")");
        }
        vh.name.setText(comment.name);
        vh.name.setCompoundDrawablesWithIntrinsicBounds(0, 0, comment
                .getUserDrawable(), 0);
        vh.name.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                vh.avatar.performClick();
            }
        });
        vh.time.setText(Utils.getDateString(comment.create_time));
        vh.content.setText(comment.content);
        vh.content.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(SpareDetailActivity.this, CommentActivity.class);
                intent.putExtra("comment", comment);
                intent.putExtra("show_keyboard", true);
                startActivity(intent);
            }
        });
        vh.dianpingCount.setText(Integer.toString(comment.recommend_num));
        if (comment.recommend_num > 0) {
            vh.dianpingCount.setText(Integer.toString(comment.recommend_num));
            vh.dianpingCount.setVisibility(View.VISIBLE);
        } else {
            vh.dianpingCount.setVisibility(View.GONE);
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.right_image:
                new AsyncTask<Void, Void, Void>() {
                    Bitmap bmp = null;

                    @Override
                    protected Void doInBackground(Void... params) {
                        bmp = ImageLoader.getInstance().loadImageSync(item.images[0]);
                        return null;
                    }

                    @Override
                    protected void onPostExecute(Void aVoid) {
                        super.onPostExecute(aVoid);
                        Utils.launchShareActivity(SpareDetailActivity.this, item.title, item
                                        .share_url, "goods", item.images[0],
                                item.description, bmp);
                    }
                }.execute();

                break;
            case R.id.spare_comment_layout:
                launchReviewListActivity();
                break;
            case R.id.spare_like_layout:
                SpareItemViewHolder.likeSpareItem(item, null, this);
                break;
            case R.id.spare_contact_button: {
                AlertDialog.Builder ab = new AlertDialog.Builder(this);
                ab.setTitle("联系人: " + item.contact_name);
                String phone = item.mobile;
                if (TextUtils.isEmpty(phone)) {
                    phone = "未填写";
                }
                ab.setItems(new String[]{"联系电话: " + phone, "私信"}, new DialogInterface
                        .OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                            case 0:
                                if (!TextUtils.isEmpty(item.mobile)) {
                                    Utils.makeCall(SpareDetailActivity.this, item.mobile);
                                }
                                break;
                            case 1: {
                                Intent intent = new Intent(SpareDetailActivity.this, ChatActivity
                                        .class);
                                intent.putExtra(ChatActivity.EXTRA_UID, item.user_id);
                                intent.putExtra(ChatActivity.EXTRA_NAME, item.contact_name);
                                intent.putExtra(ChatActivity.EXTRA_AVATAR, item.avatar);
                                startActivity(intent);
                            }
                            break;
                        }
                    }
                });
                ab.setNegativeButton(android.R.string.cancel, null);
                ab.show();
            }
            break;
        }
    }

    private void getRelatedArticles() {
        String url = NetworkConstants.GOODS_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("user_goods_id", item.user_goods_id);
        params.put("act", "get_related_article");
        LogUtils.d("before getRelatedArticles!");
        GsonRequest<ArticlesResponse> request = new GsonRequest<>(url, Method.POST,
                ArticlesResponse.class, true, params, new Listener<ArticlesResponse>() {
            @Override
            public void onResponse(ArticlesResponse response) {
                if (response.isSuccess()) {
                    bindArticles(response.data);
                } else {
                    Utils.showToast(response.msg);
                }
            }
        }, null);
        mQueue.add(request);
//        mQueue.start();
    }

    private void bindArticles(ArticleItem[] data) {
        if (data == null || data.length == 0) {
            return;
        }
        View view = getLayoutInflater()
                .inflate(R.layout.related_article_title_view, contentContainer, false);
        contentContainer.addView(view);
        int articleViewWidth = (contentContainer.getWidth() - 3 * Utils.dip2px(10)) / 2;
        int articleViewHeight = articleViewWidth * 7 / 16;
        for (int i = 0; i < data.length; i += 2) {
            View listItem = getLayoutInflater().inflate(R.layout.article_list_item,
                    contentContainer, false);
            ArticleView left = (ArticleView) listItem.findViewById(R.id.left_article);
            left.setArticle(data[i], articleViewWidth, articleViewHeight);
            if (data.length > i + 1) {
                ArticleView right = (ArticleView) listItem.findViewById(R.id.right_article);
                right.setArticle(data[i + 1], articleViewWidth, articleViewHeight);
            }
            contentContainer.addView(listItem);
        }
    }

}
